import { useMemberStore } from "@/stores"

const baseUrl =
    'https://pcapi-xiaotuxian-front-devtest.itheima.net'
const httpInterceptor = {
    // 拦截前触发
    invoke(options: UniApp.RequestOptions) {
        // 请求中没有http,需要拼接
        if (!options.url.startsWith('http')) {
            options.url = baseUrl + options.url
        }

        // 设置超时
        options.timeout = 10000
        // 自定义header
        options.header = {
            ...options.header,
            'source-client': 'miniapp'
        }
        // 添加token
        const member = useMemberStore()
        // ?.  没有的话就拿不到 不会报错
        const token = member.profile?.token
        if (token) {
            options.header.Authorization = token
        }

    }

}
// 添加拦截器
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

// 后端返回类型
interface Data<T> {
    code: string,
    msg: string,
    result: T
}
export const http = <T>(options: UniApp.RequestOptions) => {

    return new Promise<Data<T>>((resolve, reject) => {
        uni.request({
            ...options,
            success(res) {
                console.log(res.statusCode);

                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data as Data<T>)
                    // 401 登录身份过期
                } else if (res.statusCode === 401) {
                    const memberStore = useMemberStore()
                    // 清除缓存
                    memberStore.clearProfile()
                    // 跳转登录
                    uni.navigateTo({ url: '/pages/login/login' })
                    reject(res)
                } else {
                    uni.showToast({
                        title: (res.data as Data<T>).msg || '请求错误',
                        icon: 'none'
                    })
                    reject(res)
                }
                // console.log('http:',res);

            },
            fail(error) {
                uni.showToast({
                    icon: 'none',
                    title: '网络错误，换个网络试试'
                })
                reject(error)
            }
        })
    })
}